package com.example.network.parse.json

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.network.databinding.ActivityJsonBinding
import com.example.network.model.App
import com.example.network.util.HttpUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONArray
import java.io.IOException
import kotlin.concurrent.thread

class JsonActivity : AppCompatActivity() {
    private lateinit var binding: ActivityJsonBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityJsonBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        ViewCompat.setOnApplyWindowInsetsListener(view) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        sendRequestWithOkHttp()
    }

    private fun sendRequestWithOkHttp() {
        thread {
            val mocker = JsonMocker("/get_data.json")
            HttpUtil.sendOkhttpRequest(mocker.baseUrl, object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                }

                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body?.string()
                    if (responseData != null) {
                        parseJsonWithGson(responseData)
//                        parseJsonWithJsonObject(responseData)
                    }
                }
            })
        }
    }

    /**
     * 解析 json 数据
     */
    private fun parseJsonWithGson(jsonData: String) {
        try {
            val gson = Gson()
            val typeOf = object : TypeToken<List<App>>() {}
                .type
            val appList = gson.fromJson<List<App>>(jsonData, typeOf)

            val buffer = StringBuilder()
            for (app in appList) {
                buffer.append("id is ${app.id}, name is ${app.name}, version is ${app.version}\n")
            }
            showResponse(buffer.toString())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    /**
     * 解析 json 数据
     * 使用 JSONObject
     */
    private fun parseJsonWithJsonObject(jsonData: String) {
        try {
            val jsonArray = JSONArray(jsonData)
            val buffer = StringBuilder()
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                val id = jsonObject.getInt("id")
                val name = jsonObject.getString("name")
                val version = jsonObject.getInt("version")
                buffer.append("id is $id, name is $name, version is $version\n")
            }
            showResponse(buffer.toString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun showResponse(text: String) {
        runOnUiThread {
            // 在主线程中更新 UI
            binding.responseText.text = text
        }
    }

    companion object {
        const val TAG = "GsonActivity"
    }
}